'use strict';

const path = require('path');
require('dotenv').config();

module.exports = appInfo => {
  const config = {};

  config.proxy = true;
  config.ipHeaders = 'x-real-forwarded-for,x-forwarded-for,client-ip';
  config.name = appInfo.name;
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1520911541410_4096';
  config.debug = process.env.APP_DEBUG || 'false'; // 是否为debug状态
  config.schedulOpenStatus = process.env.SCHEDUL_OPEN;
  //公共sql地址
  config.sql = path.join(appInfo.baseDir, 'sql');


  config.cluster = {
    listen: {
      path: '',
      port: parseInt(process.env.SERVER_PORT) || 7008,
      hostname: '0.0.0.0',
    }
};
  config.security = {
    csrf: {
      enable: false,
    },
  };
  config.bodyParser = {
    jsonLimit: '30mb',
    formLimit: '30mb',
  };
  // 配置商家信息
  config.tinfor = {
      key: process.env.T_APP_KEY,
      secrect: process.env.T_APP_SECRET,
      session: process.env.T_SESSION
  };

  config.mysql = {
    client: {
      host: process.env.DB_HOST,
      port: process.env.DB_PORT || 3306,
      user: process.env.DB_USER,
      database: process.env.DB_NAME,
      password: process.env.DB_PASSWORD,
    },
    // 是否加载到 app 上，默认开启
    app: true,
    // 是否加载到 agent 上，默认关闭
    agent: false,
  };

  config.onerror = {
    json(err, ctx) {
      const status = detectStatus(err);
      let errorJson = {};

      this.status = status;
      const code = err.code || err.type;
      const message = detectErrorMessage(ctx, err);

      ctx.status = code;
        if (status >= 500) {
          errorJson = {
            code,
            // don't respond any error message in production env
            message: http.STATUS_CODES[status],
          };


        } else {
          // 4xx client side error
          // addition `errors`
          errorJson = {
            code,
            message,
            errors: err.errors,
            expiredIn: err.expiredIn,
          };
        }

        ctx.set({
          "Content-Type": "application/json"
        });

        ctx.body = errorJson;

      // this.body = errorJson;
    },
  };


  config.logger = {
    level: 'DEBUG',
    consoleLevel: 'DEBUG',
    dir: path.join(appInfo.baseDir, 'logs', `${appInfo.name}`),
  };


  config.api = require('./api.default')(appInfo);
  return config;
};


function detectStatus(err) {
  let status = err.status || 500;
  if (status < 200) {
    // invalid status consider as 500, like urllib will return -1 status
    status = 500;
  }
  return status;
}

function detectErrorMessage(ctx, err) {
  // detect json parse error
  if (err.status === 400 &&
      err.name === 'SyntaxError' &&
      ctx.request.is('application/json', 'application/vnd.api+json', 'application/csp-report')) {
    return 'Problems parsing JSON';
  }
  return err.message;
}

function isProd(app) {
  return app.config.env !== 'local'
      && app.config.env !== 'unittest'
      && app.config.env !== 'sit';
}
